<template>
  <!-- <el-dialog
    :title="!dataForm.tplId ? 'create' : 'modify'"
    :close-on-click-modal="false"
    :visible.sync="visible">

    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="Name" prop="eTitle">
        <el-input v-model="dataForm.eTitle" placeholder="Template Name"></el-input>
      </el-form-item>
      <el-form-item label="content" prop="eContent">
        <el-input v-model="dataForm.eContent" placeholder="content"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">Cancel</el-button>
      <el-button type="primary" @click="dataFormSubmit()">Yes</el-button>
    </span>

  </el-dialog> -->
  
  <a-modal
  :title="!sendEmailForm.tplId ? 'create' : 'modify'"
  okText="Save" 
  v-model="visible" 
  @ok="sendEmailFormSubmit">
    <div class="emailModal">
      <div class="tinfos">

        <div class="shitem">
          <div class="ltxt">Name</div>
          <div class="rshow">
            <a-input class="ipt" v-model="sendEmailForm.eTitle"/>
          </div>
        </div>

      </div>

      <div class="dbody">
        <div class="title">Content</div>
        <div class="conbox mod-demo-ueditor" v-loading="quillUpdateImg">
          
          <!-- 图片上传组件辅助-->
          <el-upload
            class="avatar-uploader"
            :action="serverUrl"
            name="img"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload">
          </el-upload>

          <quill-editor
            v-model="sendEmailForm.eContent"
            ref="myQuillEditor"
            :options="editorOption"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
            @blur="onEditorBlur($event)" 
            @focus="onEditorFocus($event)"
            id="editor"
          >
          </quill-editor>

        </div>
      </div>

    </div>
  </a-modal>

</template>

<script>
  var url = 'http://192.168.1.150:8000/renren-fast/app/imgUpload'
  const toolbarOptions = [
    ['bold', 'italic', 'underline'],  // 加粗，斜体，下划线，删除线 'strike'
    [{'color': []}, {'background': []}], // dropdown with defaults from theme
    // ['blockquote', 'code-block'], // 引用，代码块

    [{'header': 1}, {'header': 2}],  // 标题，键值对的形式；1、2表示字体大小
    [{'list': 'ordered'}, {'list': 'bullet'}],  // 列表
    [{'script': 'sub'}, {'script': 'super'}],  // 上下标
    [{'indent': '-1'}, {'indent': '+1'}],  // 缩进
    [{'align': []}],
    [{'direction': 'rtl'}],  // 文本方向

    [{'size': ['small', false, 'large', 'huge']}],  // 字体大小
    [{'header': [1, 2, 3, 4, 5, 6, false]}],  // 几级标题
    [{'font': []}],
    // ['link', 'image'],
    // ['clean']  // remove formatting button
  ]

  export default {
    data () {
      return {
        visible: false,
        sendEmailForm: {
          'tplId': 0,
          'createTime': '',
          'eTitle': '',
          'eContent': ''
        },
        // 富文本
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        serverUrl: url,  // 这里写你要上传的图片服务器地址
        // header: {token: this.$cookie.get('token')},  // 有的图片服务器要求请求头需要有token之类的参数，写在这里
        detailContent: '', // 富文本内容
        editorOption: {  // 富文本编辑器配置
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            toolbar: {
              container: toolbarOptions,  // 工具栏
              handlers: {
                'image': function (value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              }
            }
          },
          handlers: {
            'image': function (value) {
              if (value) {
                // document.querySelector('#quill-upload input').click()
                console.log('执行了image')
              } else {
                // this.quill.format('image', false)
              }
            }
          }
        },

        dataRule: {
          eTitle: [
            { required: true, message: 'Name Not null', trigger: 'blur' }
          ],
          eContent: [
            { required: true, message: 'Content Not null', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.sendEmailForm.tplId = id || 0
        this.visible = true
        this.$nextTick(() => {
          if (this.sendEmailForm.tplId) {
            this.$http({
              url: this.$http.adornUrl(`/leadsmemb/crmemailtpl/info/${this.sendEmailForm.tplId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {

              if (data && data.code === 0) {
                let obj = data.crmEmailTpl
                this.sendEmailForm.eTitle = obj.etitle
                this.sendEmailForm.eContent = obj.econtent
              }
            })
          } else {
            this.sendEmailForm.eTitle = ''
            this.sendEmailForm.eContent = ''
          }
        })
      },

      // 表单提交
      sendEmailFormSubmit () {
        // 校验
        var sendEmailForm = this.sendEmailForm
        if(!sendEmailForm.eTitle) {
          this.$message.error('Name Not null')
          return
        }

        if(!sendEmailForm.eContent) {
          this.$message.error('Content Not null')
          return
        }

        this.$http({
          url: this.$http.adornUrl(`/leadsmemb/crmemailtpl/${!this.sendEmailForm.tplId ? 'save' : 'update'}`),
          method: 'post',
          data: this.$http.adornData({
            'tplId': this.sendEmailForm.tplId || undefined,
            'etitle': this.sendEmailForm.eTitle,
            'econtent': this.sendEmailForm.eContent
          })
        }).then(({data}) => {

          if(data && data.code == 0) {
            console.log('----- save email成功 -----')
            this.$message.success('Send successfully.', 2, function () {})
            this.$emit('refreshDataList')

          } else {
            console.log('----- save email失败 -----')
            this.$message.error(data.msg)

          }

          this.visible = false
        })

      },

      // 富文本
      getContent () {
        // this.dialogVisible = true
        // var quill = new Quill('#editor', {
        //   theme: 'snow'
        // })
        // var delta = Quill.getContents()
        // console.log(delta)
      },
      // 上传图片前
      beforeUpload (res, file) {
        // 显示loading动画
        this.quillUpdateImg = true
      },
      // 上传图片成功
      uploadSuccess (res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill
        // console.log(res)
        // 如果上传成功
        if (res.code === 200) {
          console.log('执行')
          // 获取光标所在位置
          let length = quill.getSelection().index
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, 'image', res.url)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
        // loading动画消失
        this.quillUpdateImg = false
      },
      // 上传图片失败
      uploadError (res, file) {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')
      },
      onEditorBlur () { // 失去焦点事件
      },
      onEditorFocus () { // 获得焦点事件
      },
      onEditorChange () { // 内容改变事件
        // console.log(111111111, this.detailContent)
      },
      onEditorReady () {
      },

    }
  }
</script>

<style lang="scss" scoped>
// email
.emailModal {
  .tinfos {
   .shitem {
      margin-bottom: 30px;
      .ltxt {
        display: inline-block;
        width: 60px;
        font-size:14px;
        color:rgba(56,65,87,1);
      }
      .rshow {
        display: inline-block;
        font-size: 14px;
        font-weight: bold;
        color: rgba(56,65,87,1);
        .p {
          width: 400px;
          height: 30px;
          line-height: 30px;
          padding: 0 10px;
          background:#F3F6FD;
          border-radius:2px;
          border: 0;
        }
        .ant-input {
          width: 400px;
          height: 30px;
          background:#F3F6FD;
          border-radius:2px;
          border: 0;
          // border: 1px solid #1890FF;
        }
        .el-select .el-input__inner {
          width: 400px;
          height: 30px;
          background:#F3F6FD;
          border-radius:2px;
          border: 0;
        }

      }
   }
  }

  .dbody {
    margin-bottom: 30px;
    .title {
      font-size:14px;
      color:rgba(56,65,87,1);
      margin-bottom: 10px;
    }
    .conbox {
      height: 310px;
    }
  }
}

.quill-editor {
  height: 220px;
}
</style>